<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\BO\Product\ProductSkuInfoFactory;
use App\Models\Area as AreaModel;
use App\Services\Code\HttpResponse;
use App\Services\LocationService;
use App\VO\SelectCity\Builder as SelectCityVOBuilder;
use Illuminate\Http\Request;

class LocationController extends BaseController
{
    /**
     * 我的地理位置选择
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function selectCity(Request $request)
    {
        $cities = (new AreaModel())->getCities(0);
        $vo     = (new SelectCityVOBuilder())->buildList($cities);

        return $this->successJsonResult($vo);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setCity(Request $request)
    {
        $cityID     = $request->get('city_id');
        if (empty($cityID)) {
            return response()->json(HttpResponse::respFail(HttpResponse::CODE_PARAMS_ERR, 'cityid不能为空'));
        }
        $userId = $this->getUserId();
        $setRes = LocationService::setCity($cityID, $userId); //设置session状态保存到用户信息
        if ($setRes) {
            return $this->showJsonResult(200, 'ok', []);
        } else {
            return $this->showJsonResult(201, 'failed', []);
        }
    }


    /**
     * 获取城市城区
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCityAreas(Request $request)
    {
        $productSkuId = (int)$request->input('productSkuId');
        $cityId = (int)$request->input('city_id');
        if ($productSkuId) {
            try {
                $productSkuInfo = ProductSkuInfoFactory::getProductSkuInfo($productSkuId);
            } catch (\Throwable $e) {
                logException($e);
                return response()->json(HttpResponse::respFail(HttpResponse::CODE_DATA_EMPTY, '产品数据异常'));
            }
            $data = LocationService::getAntAreaDataByProduct($cityId, $productSkuInfo->getProductId());
        } else {
            $data   = LocationService::getAntAreaData();
        }

        return $this->successJsonResult($data);
    }
}
